package com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.HddcGeologicalsvyplanninglineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.HddcGeologicalsvyplanninglineRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.entity.HddcGeologicalsvyplanninglineEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.service.HddcGeologicalsvyplanninglineService;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.viewobjects.HddcGeologicalsvyplanninglineQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.viewobjects.HddcGeologicalsvyplanninglineVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-12-07
 */
@Service
public class HddcGeologicalsvyplanninglineServiceImpl implements HddcGeologicalsvyplanninglineService {

	@Autowired
    private HddcGeologicalsvyplanninglineRepository hddcGeologicalsvyplanninglineRepository;
    @Autowired
    private HddcGeologicalsvyplanninglineNativeRepository hddcGeologicalsvyplanninglineNativeRepository;

    @Override
    public JSONObject queryHddcGeologicalsvyplanninglines(HddcGeologicalsvyplanninglineQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeologicalsvyplanninglineEntity> hddcGeologicalsvyplanninglinePage = this.hddcGeologicalsvyplanninglineNativeRepository.queryHddcGeologicalsvyplanninglines(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeologicalsvyplanninglinePage);
        return jsonObject;
    }


    @Override
    public HddcGeologicalsvyplanninglineEntity getHddcGeologicalsvyplanningline(String id) {
        HddcGeologicalsvyplanninglineEntity hddcGeologicalsvyplanningline = this.hddcGeologicalsvyplanninglineRepository.findById(id).orElse(null);
         return hddcGeologicalsvyplanningline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeologicalsvyplanninglineEntity saveHddcGeologicalsvyplanningline(HddcGeologicalsvyplanninglineEntity hddcGeologicalsvyplanningline) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeologicalsvyplanningline.setUuid(uuid);
        hddcGeologicalsvyplanningline.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeologicalsvyplanningline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeologicalsvyplanningline.setIsValid("1");
        hddcGeologicalsvyplanningline.setQualityinspectionStatus("0");
        hddcGeologicalsvyplanningline.setExtends10("1");
        this.hddcGeologicalsvyplanninglineRepository.save(hddcGeologicalsvyplanningline);
        return hddcGeologicalsvyplanningline;
    }

    // 批量插入数据库
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcGeologicalsvyplanninglineEntity> saveHddcGeologicalsvyplanninglineList(List<HddcGeologicalsvyplanninglineEntity> list ) {
        for (HddcGeologicalsvyplanninglineEntity hddcGeologicalsvyplanningline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGeologicalsvyplanningline.setUuid(uuid);
            hddcGeologicalsvyplanningline.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGeologicalsvyplanningline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGeologicalsvyplanningline.setIsValid("1");
            hddcGeologicalsvyplanningline.setQualityinspectionStatus("0");
            hddcGeologicalsvyplanningline.setExtends10("1");
        }
        //List<HddcGeologicalsvyplanninglineEntity> resultList = hddcGeologicalsvyplanninglineRepository.saveAll(list);
        Iterable<HddcGeologicalsvyplanninglineEntity> iterable = hddcGeologicalsvyplanninglineNativeRepository.batchSave(list);
        return iterable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeologicalsvyplanninglineEntity updateHddcGeologicalsvyplanningline(HddcGeologicalsvyplanninglineEntity hddcGeologicalsvyplanningline) {
        HddcGeologicalsvyplanninglineEntity entity = hddcGeologicalsvyplanninglineRepository.findById(hddcGeologicalsvyplanningline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeologicalsvyplanningline);
        hddcGeologicalsvyplanningline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeologicalsvyplanningline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeologicalsvyplanninglineRepository.save(hddcGeologicalsvyplanningline);
        return hddcGeologicalsvyplanningline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeologicalsvyplanninglines(List<String> ids) {
        List<HddcGeologicalsvyplanninglineEntity> hddcGeologicalsvyplanninglineList = this.hddcGeologicalsvyplanninglineRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvyplanninglineList) && hddcGeologicalsvyplanninglineList.size() > 0) {
            for(HddcGeologicalsvyplanninglineEntity hddcGeologicalsvyplanningline : hddcGeologicalsvyplanninglineList) {
                hddcGeologicalsvyplanningline.setIsValid("0");
                hddcGeologicalsvyplanningline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvyplanningline.setUpdateTime(new Date());
                this.hddcGeologicalsvyplanninglineRepository.save(hddcGeologicalsvyplanningline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }



    @Override
    public void exportFile(HddcGeologicalsvyplanninglineQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeologicalsvyplanninglineEntity> yhDisasterEntities = hddcGeologicalsvyplanninglineNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeologicalsvyplanninglineVO> list=new ArrayList<>();
        for (HddcGeologicalsvyplanninglineEntity entity:yhDisasterEntities) {
            HddcGeologicalsvyplanninglineVO yhDisasterVO=new HddcGeologicalsvyplanninglineVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地质调查规划路线","地质调查规划路线",HddcGeologicalsvyplanninglineVO.class,"地质调查规划路线-线.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeologicalsvyplanninglineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeologicalsvyplanninglineVO.class, params);
            List<HddcGeologicalsvyplanninglineVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeologicalsvyplanninglineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeologicalsvyplanninglineVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeologicalsvyplanninglineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeologicalsvyplanninglineEntity yhDisasterEntity = new HddcGeologicalsvyplanninglineEntity();
            HddcGeologicalsvyplanninglineVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeologicalsvyplanningline(yhDisasterEntity);
        }
    }


    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeologicalsvyplanninglineEntity> hddcGeologicalsvyplanninglineList = this.hddcGeologicalsvyplanninglineRepository.queryHddcGeologicalsvyplanninglinesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvyplanninglineList) && hddcGeologicalsvyplanninglineList.size() > 0) {
            for(HddcGeologicalsvyplanninglineEntity hddcGeologicalsvyplanningline : hddcGeologicalsvyplanninglineList) {
                hddcGeologicalsvyplanningline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvyplanningline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeologicalsvyplanningline.setIsValid("0");
                this.hddcGeologicalsvyplanninglineRepository.save(hddcGeologicalsvyplanningline);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskIds
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeologicalsvyplanninglineEntity> hddcGeologicalsvyplanninglineList = this.hddcGeologicalsvyplanninglineRepository.queryHddcGeologicalsvyplanninglinesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvyplanninglineList) && hddcGeologicalsvyplanninglineList.size() > 0) {
            for(HddcGeologicalsvyplanninglineEntity hddcGeologicalsvyplanningline : hddcGeologicalsvyplanninglineList) {
                hddcGeologicalsvyplanningline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvyplanningline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeologicalsvyplanningline.setIsValid("0");
                this.hddcGeologicalsvyplanninglineRepository.save(hddcGeologicalsvyplanningline);
            }
        }

    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("SvyLineName")){
            str+="SvyLineName,";
        }
        if(!set.contains("Purpose")){
            str+="Purpose,";
        }
        if(!set.contains("SvyMethods")){
            str+="SvyMethods,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public boolean saveHddcGeologicalsvyplanninglineFromShpFiles(List<List<Object>> list,String provinceName,String cityName,String areaName,String savefilename) {
       try {
           if(list!=null&&list.size()>0){
               List<HddcGeologicalsvyplanninglineEntity> datas= new ArrayList<>();
               for(int i=0;i<list.size();i++){
                   List<Object> obs=list.get(i);
                   //HddcGeologicalsvyplanninglineVO data=new HddcGeologicalsvyplanninglineVO();
                   HddcGeologicalsvyplanninglineEntity data = new HddcGeologicalsvyplanninglineEntity();
                   data.setArea(areaName);
                   data.setProvince(provinceName);
                   data.setCity(cityName);
                   data.setExtends8(savefilename);
                   data.setId(obs.get(1).toString());
                   data.setSvylinename(obs.get(2).toString());
                   data.setPurpose(obs.get(3).toString());
                   data.setSvymethods(obs.get(4).toString());
                   data.setCommentInfo(obs.get(5).toString());
                   String pstr=obs.get(0).toString();
                   data.setExtends16("CGCS2000");
                   /*String[] ss1=pstr.split("\\(");
                   if(ss1.length>=2){
                       String[] ss2=ss1[ss1.length-1].split("\\)");
                       if(ss2.length<=2){
                           String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                           data.setExtends5(spacedata);
                       }
                   }*/
                   pstr = pstr.replace(")), ((", "#");
                   pstr = pstr.replace("), (", "#");
                   String[] ss1=pstr.split("\\(");
                   if(ss1.length>=2){
                       String[] ss2=ss1[ss1.length-1].split("\\)");
                       if(ss2.length<=2){
                           String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                           data.setExtends5(spacedata);
                       }
                   }
                   datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
               }
               deleteByCreateUser(provinceName,cityName,areaName);
               saveHddcGeologicalsvyplanninglineList(datas);
           }
           return true;
       }catch (Exception e  ){
           return false;
       }
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcGeologicalsvyplanninglineRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    //根据创建人删除数据
    public void deleteByCreateUser(String provinceName, String cityName, String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcGeologicalsvyplanninglineEntity> hddcGeologicalsvyplanninglineList = this.hddcGeologicalsvyplanninglineRepository.queryHddcGeologicalsvyplanninglinesByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvyplanninglineList) && hddcGeologicalsvyplanninglineList.size() > 0) {
            hddcGeologicalsvyplanninglineRepository.deleteAll(hddcGeologicalsvyplanninglineList);
        }
    }

    @Override
    public List<HddcGeologicalsvyplanninglineEntity> findAll() {
        List<HddcGeologicalsvyplanninglineEntity> list=this.hddcGeologicalsvyplanninglineRepository.findAll();
        return list;
    }
}
